/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PageFootnoteDialog.java
 *
 * Created on 7-Jun-2011, 11:01:30 PM
 */
package com.openbookformat.page;


import org.openbookformat.tags.FnTextTag;
import org.openbookformat.tags.FootnoteTag;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import org.apache.commons.lang.StringEscapeUtils;

/**
 *
 * @author MUFEED
 */
public class PageFootnoteDialog extends javax.swing.JDialog 
    implements HyperlinkListener {
    public static final int OK_OPTOIN = 1;
    public static final int CANCEL_OPTION = 2;
    
    /** Creates new form PageFootnoteDialog */
    public PageFootnoteDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        editor.addHyperlinkListener(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        editor = new javax.swing.JEditorPane();
        jCancel = new javax.swing.JButton();
        jOK = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        editor.setContentType("text/html");
        editor.setEditable(false);
        editor.setFont(new java.awt.Font("Tahoma", 0, 12));
        jScrollPane1.setViewportView(editor);

        jCancel.setText("Cancel");

        jOK.setText("OK");
        jOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jOKActionPerformed(evt);
            }
        });

        jButton1.setText("V<-->E");
        jButton1.setToolTipText("Left-to-Right");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 817, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 630, Short.MAX_VALUE)
                        .addComponent(jOK)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCancel)
                    .addComponent(jOK)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jOKActionPerformed
        if(editMode) {
            pageChangedCheck();
        }
        setVisible(false);
        selection = OK_OPTOIN;
    }//GEN-LAST:event_jOKActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if(editMode) {
            pageChangedCheck();
        }
        setEditMode(!editMode);
        init();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                PageFootnoteDialog dialog = new PageFootnoteDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }

    public void setMarks(ArrayList<Bookmark> marks) {
        this.marks = marks;
        setTitle("Page#" + page.getPageNumber() + " - " + marks.size() + " match[es] found.");
    }

    public FnTextTag getFnText() {
        return fnText;
    }

    public void setFnText(FnTextTag fnText) {
        this.fnText = fnText;
    }

    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
        editModeChanged();
    }
    
    private void editModeChanged() {
        if(editMode) {
            editor.setContentType("text/plain");
            jOK.setText("Apply Edit");
        } else {
            editor.setContentType("text/html");
            jOK.setText("OK");
        }
        editor.setEditable(editMode);
    }

    public boolean isLtr() {
        return ltr;
    }

    public void setLtr(boolean ltr) {
        this.ltr = ltr;
    }

    public int getSelection() {
        return selection;
    }

    public boolean isPageModified() {
        return pageModified;
    }
        
    public void init() {
        if(editMode) {
            editor.setText(page.getText());
        } else {
            
            StringBuilder buff = new StringBuilder();

            buff.append("<div style='direction:").append(ltr?
                "ltr; text-align: left;'":"rtl; text-align: right;'").
                append(">");

            //marks is empty: no footnote found
            if(marks.isEmpty()) {
                buff.append(StringEscapeUtils.escapeHtml(page.getBody()));
            } else {

                int offset = -1;
                int length = -1;
                String tStr = null;
                for(int i = 0; i < marks.size(); i++) {
                    offset = marks.get(i).getOffset();
                    length = marks.get(i).getLength();
                    tStr = page.getText().substring(offset, offset + length);

                    buff.append(StringEscapeUtils.escapeHtml(page.getBody().
                        substring(i == 0?0:marks.get(i-1).getOffset() + marks.get(i-1).getLength(),
                        marks.get(i).offset)));
                    if(marks.get(i).isSelected()) {
                        buff.append("<sup><font bgcolor='gray' color='white'>").
                            append("<a href='http://").append(i).append("'>").
                            append(StringEscapeUtils.escapeHtml(tStr)).
                            append("</a></font></sup>");
                    } else {
                        buff.append("<font bgcolor='yellow'><emp>").
                            append("<a href='http://").append(i).append("'>").
                            append(StringEscapeUtils.escapeHtml(tStr)).
                            append("</a></emp></font>");
                    }
                }
                buff.append(StringEscapeUtils.escapeHtml(page.getBody().
                        substring(marks.get(marks.size()-1).getOffset()
                        + marks.get(marks.size()-1).getLength())));
            }
            buff.append("</div>\n");

            FootnoteTag fnTag = page.getFootnote();
            buff.append(StringEscapeUtils.escapeHtml("<footnote>\n"));
            for(int i = 0; i < fnTag.size(); i++) {
                if(fnText.equals(fnTag.getFnTextTag(i))) {
                    buff.append("<font bgcolor='gray' color='white'>").
                            append(StringEscapeUtils.escapeHtml(fnTag.getFnTextTag(i).toString())).
                            append("</font>\n");
                } else {
                    buff.append(StringEscapeUtils.escapeHtml(fnTag.getFnTextTag(i) + "\n"));
                }
            }
            buff.append(StringEscapeUtils.escapeHtml("<footnote>"));
            //System.out.println(buff.toString());
            editor.setText(buff.toString().replace("\n", "<br/>"));
        }
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JEditorPane editor;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jCancel;
    private javax.swing.JButton jOK;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    private Page page;
    private ArrayList<Bookmark> marks;
    private FnTextTag fnText;
    private boolean editMode = false;
    private boolean ltr = true;
    private int selection = CANCEL_OPTION;
    private boolean pageModified = false;
    
    @Override
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            int idx = Integer.parseInt(e.getURL().getHost());
            marks.get(idx).setSelected(!marks.get(idx).isSelected());
            init();
        }
    }

    private void pageChangedCheck() {
        if(!editor.getText().equals(page.getText())) {
            int opt = JOptionPane.showConfirmDialog(rootPane, 
                    "The page has been modified. Apply changes?", 
                    "Apply page modification", 
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if(opt == JOptionPane.YES_OPTION) {
                pageModified = true;
                setVisible(false);
                page.setText(editor.getText());
                return;
            }
        }
    }

    public ArrayList<Bookmark> getMarks() {
        return marks;
    }
    
    
}
